const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const handleBlogRouter = (req, res) => {
  const {method, url} = req
  const path = url.split('?')[0]
  const id = req.query.id

  // 获取博客列表
  if (method === 'GET' && path === "/api/blog/list") {
    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    const results = getList(author, keyword)
    return  results.then(listData => new SuccessModel(listData))
  }

  // 获取博客详情
  if (method === 'GET' && path === "/api/blog/detail") {
    const data = getDetail(id)
    return data.then(res => {
      return new SuccessModel(res)
    })
  }

  // 新建一篇博客
  if (method === 'POST' && path === "/api/blog/new") {
    req.body.author = 'zhangsan'
    const result = newBlog(req.body)
    return result.then(data => {
      return new SuccessModel(data)
    })
  }

  // 更新一篇博客
  if (method === 'PUT' && path === "/api/blog/update") {
    const data = updateBlog(id, req.body)
    return data.then(val => {
      if (val) {
        return new SuccessModel(val)
      }
      return new ErrorModel(val)
    })
  }

  // 删除一篇博客
  if (method === 'POST' && path === "/api/blog/delete") {
    const author = 'zhangsan'
    const data = deleteBlog(id, author)
    return data.then(val => {
      if (val) {
        return new SuccessModel('删除成功')
      } else {
        return new ErrorModel('删除失败')
      }
    })
  }
}

module.exports = handleBlogRouter